package com.lucfzy.log.consumer;

import com.lucfzy.log.dto.AppLoggerInfo;
import com.lucfzy.log.dto.ESResponseDTO;
import com.lucfzy.rabbitmq.MessageQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

/**
 * 日志消息消费
 *
 * @author lucfzy
 * @ClassName AppLogMsgListener
 * @description 日志消息消费
 * @created 2021-07-25 09:40
 **/
@Component
@RabbitListener(queues = MessageQueue.APPLOG)
public class AppLogMsgListener {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RestTemplate restTemplate;

    @RabbitHandler
    public void onMessage(@Payload String msg) {
        AppLoggerInfo input = AppLoggerInfo.builder().msg(msg).build();
        ESResponseDTO response = restTemplate.postForObject("http://localhost:9200/logs/applog/", input, ESResponseDTO.class);
        // 记录异常情况
        afterValidateSuccessInfo(response);
        // 打印生成的id，用于索引数据
        String id = response.get_id();
        log.warn("数据插入es中的id信息为: {}", id);
    }

    /**
     * 校验信息不为空
     */
    private void afterValidateSuccessInfo(ESResponseDTO response) {
        if (Objects.isNull(response)) {
            throw new RuntimeException("数据写入es失败");
        }
        // 记录异常情况
        if (response.get_shards().getSuccessful() <= 0 && response.get_shards().getFailed() > 0) {
            throw new RuntimeException("日志数据插入es失败。");
        }
    }

}
